﻿using System;
using System.Collections.Generic;
using AutoStopApp.Core;
using AutoStopData.BussinessLogic;
using AutoStopData.Model;
using Telerik.Web.UI;

namespace AutoStopApp.Controls
{
    public partial class TripSearch : AjaxUserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            SearchButton.Click += SearchButtonClick;
            ucTripGrid.GridInstance.NeedDataSource += GridInstanceNeedDataSource;
            Load += PageLoad;
        }

        void PageLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillRegions(cbxInitialRegion);
                FillRegions(cbxDestinationRegion);
            }
        }

        void GridInstanceNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var searchResults = new List<Trip>();
            if (IsPostBack)
            {
                searchResults = Trips.Search(txtInitialCity.Text, cbxInitialRegion.SelectedValue, datDepartureTime.SelectedDate, txtDestinationCity.Text, cbxDestinationRegion.SelectedValue, datArrivalTime.SelectedDate);
            }
            ucTripGrid.GridInstance.DataSource = searchResults;
        }

        void SearchButtonClick(object sender, EventArgs e)
        {
            ucTripGrid.GridInstance.Rebind();
        }

        private static void FillRegions(RadComboBox comboBox)
        {
            comboBox.Items.Clear();
            comboBox.Items.AddRange(AutoStopApp.Controls.TripList.GetAllRegions());
        }

        public Guid? GetCurrentUserId()
        {
            var currentSession = SessionProvider.CurrentSession;
            var currentUserId = currentSession == null ? (Guid?)null : currentSession.User.UserId;
            return currentUserId;
        }
    }
}